package monster.com.cvh.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.Permission;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISCameraConfig;
import com.yuyh.library.imgsel.config.ISListConfig;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import monster.com.cvh.R;
import monster.com.cvh.activity.LoginActivity;
import monster.com.cvh.adapter.UserMessageFragmentAdaper;
import monster.com.cvh.bean.AvatorBean;
import monster.com.cvh.bean.ResumeMessageBean;
import monster.com.cvh.bean.UserMessageInfoBean;
import monster.com.cvh.constant.Constans;
import monster.com.cvh.event.RefreshCompletedEvent;
import monster.com.cvh.event.VisitorRefreshEvent;
import monster.com.cvh.fragment.base.PermissionFragment;
import monster.com.cvh.util.CheckNetUtils;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import okhttp3.Call;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;
import static monster.com.cvh.constant.Constans.FINISH;
import static monster.com.cvh.constant.Constans.NO_DATA;

/**
 * @author: 13580
 * @data: 2018/3/14
 * @function:简历Tab 用户信息Fragment
 */

public class UserMessageFragment extends PermissionFragment implements View.OnClickListener, Observer {
    private static final int REQUEST_CAMERA_CODE = 1001;//拍照
    private static final int REQUEST_LIST_CODE = 1002;//选图片
    private static final String TAG = "UserMessageFragment";
    @BindView(R.id.rv_fragment_user)
    RecyclerView mRecyclerView;
    @BindView(R.id.srl_fragment_user_message)
    SwipeRefreshLayout mSwipeRefreshLayout;
    private UserMessageFragmentAdaper mAdapter;
    private View mHeader;
    private BaseBottomDialog mBottomDialog;
    private CircleImageView mAvatar;
    private String mToken;
    private ProgressDialog mDialog;
    private Tiny.FileCompressOptions mOptions;
    private ResumeMessageBean mResumeMessageBean;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RefreshCompletedEvent.getInstance().addObserver(this);
        VisitorRefreshEvent.getInstance().addObserver(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        RefreshCompletedEvent.getInstance().deleteObserver(this);
        VisitorRefreshEvent.getInstance().deleteObserver(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_user_message;
    }

    @Override
    protected void initData() {
        mToken = SPUtils.getString(getActivity(), "token", "");
        Log.e(TAG, "token的值: " + mToken);
        //初始化弹窗
        mDialog = new ProgressDialog(getContext());
        mDialog.setMessage(getResources().getString(R.string.wait));
        mDialog.setCanceledOnTouchOutside(false);
        //设置刷新时动画的颜色，可以设置4个
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        //压缩图片
        mOptions = new Tiny.FileCompressOptions();
        //请求数据
        if (isLogined() && CheckNetUtils.checkState_21()) {
            loadData();
        } else {
            ArrayList<UserMessageInfoBean> list = new ArrayList<>();
            list.add(new UserMessageInfoBean("个人信息", NO_DATA));
            list.add(new UserMessageInfoBean("求职意向", NO_DATA));
            list.add(new UserMessageInfoBean("教育经历", NO_DATA));
            list.add(new UserMessageInfoBean("荣誉证书", NO_DATA));
            list.add(new UserMessageInfoBean("在校经历", NO_DATA));
            list.add(new UserMessageInfoBean("工作经历", NO_DATA));
            list.add(new UserMessageInfoBean("职业技能", NO_DATA));
            list.add(new UserMessageInfoBean("资格证书", NO_DATA));
            list.add(new UserMessageInfoBean("项目经验", NO_DATA));
            list.add(new UserMessageInfoBean("自我评价", NO_DATA));
            mAdapter = new UserMessageFragmentAdaper(list);
            mHeader = LayoutInflater.from(getActivity()).inflate(R.layout.item_fragment_user_message_header, null, true);
            mAvatar = (CircleImageView) mHeader.findViewById(R.id.iv_fragment_user_avatar);
            Glide.with(getActivity())
                    .load(R.mipmap.resume_avatar)
                    .into(mAvatar);
            mAvatar.setOnClickListener(this);
            mAdapter.addHeaderView(mHeader);
            mAdapter.setNewData(list);
            mRecyclerView.setAdapter(mAdapter);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        }
    }

    @Override
    protected void initEvent() {
        //初始化弹窗
        mBottomDialog = BottomDialog.create(getActivity().getSupportFragmentManager())
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        v.findViewById(R.id.tv_user_fragment_dialog_gallery).setOnClickListener(UserMessageFragment.this);
                        v.findViewById(R.id.tv_user_fragment_dialog_camera).setOnClickListener(UserMessageFragment.this);
                        v.findViewById(R.id.tv_user_fragment_dialog_cancel).setOnClickListener(UserMessageFragment.this);
                    }
                })
                .setDimAmount(0.3f)
                .setLayoutRes(R.layout.dialog_take_photo)
                .setTag("GetImageDialog");

        // 自定义图片加载器
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                boolean logined = isLogined();
                Log.e(TAG, "onRefresh: " + logined);
                if (logined) {
                    loadData();
                } else {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    /**
     * 获取简历首页
     */
    private void loadData() {
        OkGo.<String>get(MyConstant.LOAD_RESUME_DATA)
                .tag(this)
                .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e(TAG, "onSuccess: "+s );
                        try {
                            mResumeMessageBean = new Gson().fromJson(s, ResumeMessageBean.class);
                           if (mResumeMessageBean.getCode()!=1){
                                goToLogin();
                                return;
                            }
                            ArrayList<UserMessageInfoBean> list = new ArrayList<>();
                            list.add(new UserMessageInfoBean("个人信息", mResumeMessageBean.getData().getBasic().checkouComplete()));
                            list.add(new UserMessageInfoBean("求职意向", mResumeMessageBean.getData().getJob_prefer().checkouComplete()));
                            list.add(new UserMessageInfoBean("教育经历", mResumeMessageBean.getData().isCompleteFormList(mResumeMessageBean.getData().getEdu_exps())));
                            list.add(new UserMessageInfoBean("荣誉证书", mResumeMessageBean.getData().isCompleteFormList(mResumeMessageBean.getData().getHonor_exps())));
                            list.add(new UserMessageInfoBean("在校经历", mResumeMessageBean.getData().isCompleteFormList(mResumeMessageBean.getData().getSchool_exps())));
                            list.add(new UserMessageInfoBean("工作经历", mResumeMessageBean.getData().isCompleteFormList(mResumeMessageBean.getData().getWork_exps())));
                            list.add(new UserMessageInfoBean("职业技能", mResumeMessageBean.getData().isCompleteFormList(mResumeMessageBean.getData().getSkills())));
                            list.add(new UserMessageInfoBean("资格证书", mResumeMessageBean.getData().isCompleteFormList(mResumeMessageBean.getData().getQulifications())));
                            list.add(new UserMessageInfoBean("项目经验", mResumeMessageBean.getData().isCompleteFormList(mResumeMessageBean.getData().getProject_exps())));
                            String selfIntro = mResumeMessageBean.getData().getSelf_intro();
                            if (selfIntro == null || selfIntro.isEmpty()) {
                                list.add(new UserMessageInfoBean("自我评价", NO_DATA));
                            } else {
                                list.add(new UserMessageInfoBean("自我评价", FINISH));
                            }
                            mAdapter = new UserMessageFragmentAdaper(list);
                            mHeader = LayoutInflater.from(getActivity()).inflate(R.layout.item_fragment_user_message_header, null, true);
                            mAvatar = (CircleImageView) mHeader.findViewById(R.id.iv_fragment_user_avatar);
                            Glide.with(getActivity())
                                    .load(mResumeMessageBean.getData().getIcon_url())
                                    .error(R.mipmap.resume_avatar)
                                    .into(mAvatar);
                            mAvatar.setOnClickListener(UserMessageFragment.this);
                            mAdapter.addHeaderView(mHeader);
                            mAdapter.setNewData(list);
                            mRecyclerView.setAdapter(mAdapter);
                            mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                            showToastShort(R.string.net_load_failed);
                        } finally {
                            if (mSwipeRefreshLayout != null) {
                                mSwipeRefreshLayout.setRefreshing(false);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        showToastShort(R.string.net_load_failed);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }

                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击头像
            case R.id.iv_fragment_user_avatar:
                if (!isLogined()) {
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    intent.putExtra(Constans.VISITOR, Constans.LOGIN_WITHOUT_OPTION);
                    startActivityForResult(intent, Constans.LOGIN_WITHOUT_OPTION);
                    return;
                }
                if (mBottomDialog != null) {
                    mBottomDialog.show(getActivity().getSupportFragmentManager());
                }
                break;
            //从图库中选择
            case R.id.tv_user_fragment_dialog_gallery:
                takePhoto(new Action() {
                    @Override
                    public void onAction(Object data) {
                        openGallery();
                    }
                });
                break;
            //拍照
            case R.id.tv_user_fragment_dialog_camera:
                takePhoto(new Action() {
                    @Override
                    public void onAction(Object data) {
                        opeanCamera();
                    }
                });
                break;
            //取消选择更换头像
            case R.id.tv_user_fragment_dialog_cancel:
                mBottomDialog.dismiss();
                break;
        }
    }

    private void takePhoto(Action action) {
        requestPermission(
                action,
                null,
                Permission.CAMERA,
                Permission.READ_EXTERNAL_STORAGE
        );
        if (mBottomDialog != null) {
            mBottomDialog.dismiss();
        }
    }

    private void openGallery() {
        // 自由配置选项
        ISListConfig config = new ISListConfig.Builder()
                // 是否多选, 默认true
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.TRANSPARENT)
                // “确定”按钮文字颜色
                .btnTextColor(getResources().getColor(R.color.white))
                // 使用沉浸式状态栏
                .statusBarColor(getResources().getColor(R.color.colorPrimary))
                // 返回图标ResId
                .backResId(R.mipmap.general_back)
                // 标题
                .title("请选择图片")
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar背景色
                .titleBgColor(getResources().getColor(R.color.colorPrimary))
                // 第一个是否显示相机，默认true
                .needCamera(true)
                .needCrop(true)
                .build();
        // 跳转到图片选择器
        ISNav.getInstance().toListActivity(this, config, REQUEST_LIST_CODE);
    }

    private void opeanCamera() {
        ISCameraConfig config = new ISCameraConfig.Builder()
                .needCrop(true) // 裁剪
                .cropSize(1, 1, 200, 200)
                .build();
        ISNav.getInstance().toCameraActivity(this, config, REQUEST_CAMERA_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK && data != null) {
            uploadFormCamera(data);
        }

        if (requestCode == REQUEST_LIST_CODE && resultCode == RESULT_OK && data != null) {
            uploadFromGallery(data);
        }
    }

    /**
     * 上传图库的返回的照片
     *
     * @param data
     */
    private void uploadFromGallery(Intent data) {
        mDialog.show();
        List<String> pathList = data.getStringArrayListExtra("result");
        String photo = pathList.get(0);
        if (photo != null) {
            Tiny.getInstance().source(photo).asFile().withOptions(mOptions).compress(new FileCallback() {
                @Override
                public void callback(boolean isSuccess, final String outfile, Throwable t) {
                    if (isSuccess) {
                        OkGo.put(MyConstant.ALERT_RESUNE_AVATER)
                                .tag(UserMessageFragment.this)
                                .params(MyConstant.TOKEN, mToken)
                                .params(MyConstant.ICON, new File(outfile))
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        Log.e(TAG, "图片上传发成功: " + s);
                                        try {
                                            AvatorBean avatorBean = new Gson().fromJson(s, AvatorBean.class);
                                            if (avatorBean.getCode() == 1) {
                                                showToastShort(R.string.upload_image_success);
                                                Glide.with(getActivity())
                                                        .load(outfile)
                                                        .into(mAvatar);
                                                SPUtils.putString(getActivity(), Constans.SP_RESUME_AVATOR_KEY, avatorBean.getData().getIconURL());
                                            }
                                        } catch (JsonSyntaxException e) {
                                            e.printStackTrace();
                                        } catch (Resources.NotFoundException e) {
                                            e.printStackTrace();
                                        } finally {
                                            mDialog.dismiss();
                                        }
                                    }

                                    @Override
                                    public void onError(Call call, Response response, Exception e) {
                                        mDialog.dismiss();
                                        showToastShort(R.string.upload_image_fail);
                                    }
                                });

                    } else {
                        mDialog.dismiss();
                        showToastShort(R.string.compress_failed);
                    }
                }
            });
        } else {
            mDialog.dismiss();
            Log.e(TAG, "图库返回的图片路径为空");
        }
    }

    /**
     * 上传相机返回的照片
     *
     * @param data
     */
    private void uploadFormCamera(Intent data) {
        mDialog.show();
        final String path = data.getStringExtra("result");
        Tiny.getInstance().source(path).asFile().withOptions(mOptions).compress(new FileCallback() {
            @Override
            public void callback(boolean isSuccess, final String outfile, Throwable t) {
                if (isSuccess) {
                    OkGo.put(MyConstant.ALERT_RESUNE_AVATER)
                            .tag(UserMessageFragment.this)
                            .params(MyConstant.TOKEN, mToken)
                            .params(MyConstant.ICON, new File(outfile))
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    try {
                                        AvatorBean avatorBean = new Gson().fromJson(s, AvatorBean.class);
                                        if (avatorBean.getCode() == 1) {
                                            showToastShort(R.string.upload_image_success);
                                            Glide.with(getActivity())
                                                    .load(outfile)
                                                    .into(mAvatar);
                                            SPUtils.putString(getActivity(), Constans.SP_RESUME_AVATOR_KEY, avatorBean.getData().getIconURL());
                                        }
                                    } catch (JsonSyntaxException e) {
                                        e.printStackTrace();
                                    } catch (Resources.NotFoundException e) {
                                        e.printStackTrace();
                                    } finally {
                                        mDialog.dismiss();
                                    }
                                }

                                @Override
                                public void onError(Call call, Response response, Exception e) {
                                    mDialog.dismiss();
                                    showToastShort(R.string.upload_image_fail);
                                }
                            });

                } else {
                    mDialog.dismiss();
                    showToastShort(R.string.compress_failed);
                }
            }
        });
    }

    /**
     * 监听信息填写刷新完成度
     *
     * @param observable
     * @param o
     */
    @Override
    public void update(Observable observable, Object o) {
        if (observable instanceof RefreshCompletedEvent) {
            mSwipeRefreshLayout.setRefreshing(true);
            loadData();
        }
        if (observable instanceof VisitorRefreshEvent) {
            loadData();
        }
    }
}
